package org.jeecg.modules.lab.syn;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.cronJob.MyEnum;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
@Component
public class CopySqlJob  {


@XxlJob(value = "CopySqlJob")
    public ReturnT<String> execute(String params)  {
        String scriptsFolderPath = MyEnum.scriptsFolderPath;
        String backupFolderPath = MyEnum.backupFolderPath;
        File folder = new File(scriptsFolderPath);
        File[] scriptFiles = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".sql"));
        if (scriptFiles != null) {
            try (
                    Connection conn = DatabaseConnectionManager.getDataSource().getConnection()
            ) {
                conn.setAutoCommit(false); // 关闭自动提交，启用手动提交事务
                for (File scriptFile : scriptFiles) {
                    StringBuilder sqlBuilder = new StringBuilder();
                    try (BufferedReader reader = new BufferedReader(new FileReader(scriptFile))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sqlBuilder.append(line);
                            sqlBuilder.append("\n");
                        }
                    }
                    if (sqlBuilder.length()!=0){
                        try (Statement stmt = conn.createStatement()) {
                            stmt.execute(sqlBuilder.toString());
                            // 复制到备份文件夹
                            Path sourcePath = scriptFile.toPath();
                            Path destPath = Paths.get(backupFolderPath, scriptFile.getName());
                            Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
                            scriptFile.delete();
                        } catch (SQLException e) {
                            System.out.println("错误sql"+e);
                            conn.rollback(); // 回滚事务
                        }
                    }else {
                        //删除空sql脚本
                        scriptFile.delete();
                    }
                }
                conn.commit(); // 提交事务
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    return ReturnT.SUCCESS;
    }
}
